import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayLoadDto } from './dto/jwt-payload.dto';
import { AccountService } from '../users/services/account.service';
import { IAccount } from '../users/interface/account.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {

  constructor(private readonly accountService: AccountService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secret'
    });
  }

  async validate(jwtPayLoad: JwtPayLoadDto): Promise<IAccount> {
    const user = await this.accountService.getAccountByName(jwtPayLoad.userName);
    if (user === null) {
      throw new UnauthorizedException();
    }
    return user;
  }

}